#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    udpSocket = new QUdpSocket(this);
    connect(udpSocket,SIGNAL(readyRead()),this,SLOT(recv_data()));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_clicked()
{
   // QByteArray msg = ui->textEdit->toPlainText().toLatin1();
    QString msg = ui->textEdit->toPlainText();
    udpSocket->writeDatagram(msg.toUtf8(),QHostAddress::LocalHost,8888);
    //udpSocket->writeDatagram(msg,QHostAddress("192.168.12.72"),8888);
    ui->textEdit->clear();
    qDebug()<< "send ok";
}
void Widget::recv_data(){
    while (udpSocket->hasPendingDatagrams()) {
        qDebug()<<"111";
            QByteArray datagram;
            datagram.resize(udpSocket->pendingDatagramSize());
//            QHostAddress sender;
//            quint16 senderPort;
             udpSocket->readDatagram(datagram.data(), datagram.size());

            QString message = QString::fromUtf8(datagram);
           ui->textEdit_2->append("server: "+message);
//           QByteArray response = ("Echo: " + message).toUtf8();
//          udpSocket->writeDatagram(response, sender, senderPort);
        }
}
